In this tutorial, we will learn how to access DOM elements using IDs or refs. Sometimes, we have direct access to an element. To retrieve an element by its ID, we can use the document.getElementById method. In the second example, we will use Vue 3 and refs to access the element.
How to use Vue js to retrieve an element by its ID in the DOM?
In the example below, we use document.getElementById to retrieve the DOM element. You can use this code to edit and customize it in the TryIt editor.
Vue document.getelementbyid Example
<script type="module">
import {createApp} from "vue";
createApp({
data() {
return {};
},
methods: {
getElementByIdExample() {
const element = document.getElementById('myElement');
if (element) {
console.log('Element found:', element);
} else {
console.log('Element not found!');
}
}
},
}).mount("#app");
</script>
How to use Ref attributes to get elements in Vue 3?
In the example below, we illustrate how to use the ref attribute in Vue 3 to access a DOM element. By assigning the ref attribute to an element in the template and defining a reference name, you can easily manipulate its color, size, or any animation in Vue methods
Vue 3 Get Element by Id
<script type="module">
const {createApp,ref} = Vue;
createApp({
setup() {
const myElement = ref(null);
const changeColor = () => {
myElement.value.style.color = 'red';
};
return {
myElement,
changeColor
};
}
}).mount("#app");
</script>
Output of Vue Get Element by Ref








